package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

/**
 * Performs user dao operations
 * @author Sukhjinder
 */
class UserSqlDao implements UserDao {
	
	// Connection
	private Connection conn;
	
	// Statements
    private final String INSERT = "INSERT INTO users VALUES(?);";
    private final String SELECTBYNAME = "SELECT * FROM users WHERE Id = ?;";
    private final String UPDATE = "UPDATE users " +
    		"SET Name = ? " +
    		"WHERE Id = ?;";
    private final String DELETE = "DELETE FROM users WHERE Id = ?;";
    
    /**
     * Constructor
     * @param conn connection object for database
     */
    public UserSqlDao(Connection conn) {
		this.conn = conn;
	}

	@Override
    public int insert(Map<String, String> properties) throws Exception {
        PreparedStatement statement = conn.prepareStatement(INSERT); 
        conn.setAutoCommit(true);
        int userId=-1;
        
        statement.setString(1, properties.get("name"));
        statement.executeUpdate();
        
        ResultSet rs = statement.getGeneratedKeys();
        if (rs.next()){
        	userId=rs.getInt(1);
        }
        rs.close();
        
        return userId;
                
    }

	@Override
    public Map<String, String> load(String name) throws Exception {
        Map<String, String> properties = new HashMap<>();

        PreparedStatement statement = conn.prepareStatement(SELECTBYNAME);
        statement.setString(1, name);
        ResultSet rs = statement.executeQuery();
        if (rs.next() == false) {
        	properties.put("error", "Record not found");
        } else {
        	properties.put("id", rs.getString(1));
        }
        rs.close();
            
        return properties;
    }

    @Override
    public void update(Map<String, String> properties) throws Exception {
        PreparedStatement statement = conn.prepareStatement(UPDATE);
        conn.setAutoCommit(true);
        statement.setString(1, properties.get("name"));
        statement.setString(2, properties.get("id"));
        statement.executeUpdate();
    }

	@Override
	public void delete(int id) throws Exception {
		PreparedStatement statement = conn.prepareStatement(DELETE);
        conn.setAutoCommit(true);
        statement.setString(1, String.valueOf(id));
        statement.executeUpdate();
	}
}
